<?php
// +-----------------+-------------------------------------------------------------------------------------------------------+------+-----+---------+----------------+
// | Field           | Type                                                                                                  | Null | Key | Default | Extra          |
// +-----------------+-------------------------------------------------------------------------------------------------------+------+-----+---------+----------------+
// | id              | int(11)                                                                                               | NO   | PRI | NULL    | auto_increment |
// | user_id         | int(11) unsigned                                                                                      | NO   |     | 0       |                |
// | article_id      | int(11) unsigned                                                                                      | NO   |     | 0       |                |
// | title           | varchar(255)                                                                                          | NO   |     |         |                |
// | user_name       | varchar(50)                                                                                           | NO   |     |         |                |
// | birthday        | date                                                                                                  | YES  |     | NULL    |                |
// | id_num          | varchar(18)                                                                                           | YES  |     |         |                |
// | gender          | enum('secret','male','female','unknown')                                                              | YES  |     | secret  |                |
// | pro_title       | varchar(30)                                                                                           | YES  |     |         |                |
// | education       | enum('secret','zhongji','zhongzhuan','gaozhong','dazhuan','benke','shuoshi','boshi','boshihou','mba') | YES  |     | secret  |                |
// | email           | varchar(100)                                                                                          | YES  |     |         |                |
// | mobile          | varchar(15)                                                                                           | YES  |     |         |                |
// | college_name    | varchar(50)                                                                                           | YES  |     |         |                |
// | college_type    | varchar(30)                                                                                           | YES  |     |         |                |
// | college_no      | varchar(30)                                                                                           | YES  |     |         |                |
// | college_depart  | varchar(30)                                                                                           | YES  |     |         |                |
// | attachment_path | varchar(255)                                                                                          | YES  |     |         |                |
// | member_id       | int(11) unsigned                                                                                      | YES  |     | 0       |                |
// | create_time     | int(11) unsigned                                                                                      | YES  |     | 0       |                |
// | update_time     | int(11) unsigned                                                                                      | YES  |     | 0       |                |
// | delete_time     | int(11) unsigned                                                                                      | YES  |     | 0       |                |
// | attachment_name     | varchar(255)                                                                                          | YES  |     |         |                |
// +-----------------+-------------------------------------------------------------------------------------------------------+------+-----+---------+----------------+
namespace app\common\model;

use think\facade\Config;
use think\facade\Cache;
use app\common\model\Base;
use app\common\validate\Apply as Validate;

class Apply extends Base
{
    /**
     * BelongsTo 栏目
     * @Author   zhanghong(Laifuzi)
     * @DateTime 2018-06-19
     * @return   [type]             [description]
     */
    public function user()
    {
        return $this->belongsTo('User', 'user_id')->bind([
                'user_login_name'  => 'name',
                'user_mobile'  => 'mobile',
            ]);;
    }

    /**
     *  BelongsTo 栏目分类
     * @Author   zhanghong(Laifuzi)
     * @DateTime 2018-06-19
     * @return   [type]             [description]
     */
    public function article()
    {
        return $this->belongsTo('Article', 'article_id')->bind([
                'article_title'  => 'title',
            ]);
    }

    /**
     * 与AuthGroup BelongsTo关联设置
     * @Author   zhanghong(Laifuzi)
     * @DateTime 2018-06-07
     * @return   array              [description]
     */
    public function member()
    {
        return $this->belongsTo('Member')->bind([
                'member_name'  => 'name',
            ]);
    }

    /**
     * 列表搜索方法
     * @Author   zhanghong(Laifuzi)
     * @DateTime 2018-06-07
     * @param    array              $param     搜索参数
     * @param    integer            $page_rows 每页显示数量
     * @return   Paginate
     */
    public function minePaginate($param, $page_rows = 0)
    {
        if($page_rows < 1){
            $page_rows = Config::get('paginate.list_rows');
        }

        $map = $this->parseSearchParam($param);

        $config = [];
        $config["query"] = $param;
        // 分页参数名是 page ，paginate方法内有获取到该值的方法
        $page = 1;
        if(isset($param["page"])){
            $page = intval($param["page"]);
        }
        $config["page"] = $page;

        $order_type = '';
        if(isset($param['order'])){
            $order_type = $param['order'];
        }
        $order_str = $this->queryOrderStr($order_type);

        $paginate = $this->with('user,article')->where($map)->order($order_str)->paginate($page_rows, false, $config);
        return $paginate;
    }

    /**
     * 导出申报项目记录
     * @Author   zhanghong(Laifuzi)
     * @DateTime 2018-06-21
     * @param    [type]             $param [description]
     * @return   [type]                    [description]
     */
    public function exportExcel($param)
    {
        $date_str = date('Y-m-d', time());
        $objPHPExcel = new \PHPExcel();
        $objPHPExcel->getProperties()
                     ->setCreator('laifuzi') //设置创建者
                     ->setLastModifiedBy($date_str) //设置时间
                     ->setTitle('项目申报信息'); //设置类别

        $activeSheet = $objPHPExcel->getActiveSheet();
        $activeSheet->setTitle("项目申报信息");

        // 设置导出Excel的标题
        $headers = $this->exportHeaders();
        $row_idx = 1;
        foreach ($headers as $col_idx => $header) {
          $activeSheet->setCellValueByColumnAndRow($col_idx, $row_idx, $header['title']);
        }

        $page = 1;
        $per_page = 100; // 每次查询数量
        while(true){
            $param['page'] = $page++;
            $res = $this->minePaginate($param, $per_page);
            $list = $res->all();
            foreach ($list as $key => $item) {
                $row_idx++;
                $col_idx = 0;
                foreach ($headers as $col_idx => $header) {
                    $name = $header['name'];
                    $cell_value = $item[$name];
                    if(empty($cell_value) && isset($header['default'])){
                        $cell_value = $header['default'];
                    }
                    $activeSheet->setCellValueByColumnAndRow($col_idx, $row_idx, $cell_value);
                }
            }

            // 已经到最后一页
            if($page >= $res->lastPage()){
                break;
            }
        }

        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="apply_'.date("mdH").'.xls"');
        header('Cache-Control: max-age=0');
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
    }

    /**
     * 用户前台列表搜索方法
     * @Author   zhanghong(Laifuzi)
     * @DateTime 2018-06-20
     * @param    array              $param     用户请求参数
     * @param    integer            $page_rows [description]
     * @return   array                         [description]
     */
    public function userPaginate($param, $page_rows = 0)
    {
        if($page_rows < 1){
            $page_rows = Config::get('paginate.list_rows');
        }

        $default_param = [
            'only_active' => 1,
        ];
        $query_param = array_merge($param, $default_param);
        $map = $this->parseSearchParam($query_param);

        $config = [];
        // 过滤Paginate的分页参数
        $paginate_param = [];
        $allow_names = ['order'];
        foreach ($param as $key => $name) {
            if(isset($param[$name]) && $param[$name] != ''){
                $paginate_param[$name] = $param[$name];
            }
        }
        $config["query"] = $paginate_param;

        // 分页参数名是 page ，paginate方法内有获取到该值的方法
        $page = 1;
        if(isset($param["page"])){
            $page = intval($param["page"]);
        }
        $config["page"] = $page;

        $order_type = '';
        if(isset($param['order'])){
            $order_type = $param['order'];
        }
        $order_str = $this->queryOrderStr($order_type);
        $select_fields = [
            'id', 'article_id', 'user_id', 'title',
            "FROM_UNIXTIME(create_time, '%Y-%m-%d') AS create_date",
            "FROM_UNIXTIME(create_time, ' %H:%i:%S') AS create_hour",
        ];
        $paginate = $this->field($select_fields)->where($map)->order($order_str)->paginate($page_rows, false, $config);
        return $paginate;
    }

    /**
     * 用户查看单条记录
     * @Author   zhanghong(Laifuzi)
     * @DateTime 2018-06-19
     * @param    integer            $id              主键ID
     * @return   array                               [description]
     */
    public function userFind($id){
        $current_user_id = login_user_id();
        $select_fields = [
            "*",
            "FROM_UNIXTIME(create_time, '%Y-%m-%d') AS create_date",
        ];
        $item = $this->with('article')->field($select_fields)->where('id', intval($id))->find();
        if(empty($item)){
            return [];
        }else if($item['user_id'] != $current_user_id){
            return [];
        }
        return $item;
    }

    /**
     * 查询用户指定article的报名信息
     * @Author   zhanghong(Laifuzi)
     * @DateTime 2018-06-28
     * @param    [type]             $article_id [description]
     * @return   [type]                         [description]
     */
    public function findUserArticleItem($article_id){
        $current_user_id = login_user_id();
        $item = $this->where('user_id', $current_user_id)->where('article_id', intval($article_id))->find();
        return $item;
    }

    /**
     * 添加或更新记录
     * @Author   zhanghong(Laifuzi)
     * @DateTime 2018-06-07
     * @param    array              $data 表单提交数据
     * @param    integer            $id   主键ID
     * @return   array                    更新结果
     */
    public function createOrUpdate($data, $id = 0)
    {
        $res = ['status' => false, 'data' => [], 'msg' => "提交或更新项目申报失败"];
        if($id > 0){
            $data['id'] = $id;
        }

        $data['user_id'] = login_user_id();
        if(isset($data['id'])){
            $item = $this->where('id', $data['id'])->find();
            if(empty($item)){
                $res['msg'] = '未找到要更新的项目申报记录';
                return $res;
            }else if($item['user_id'] != $data['user_id']){
                $res['msg'] = '您没有权限更新该申报记录';
                return $res;
            }
        }

        // 同一项目每个用户只能申报一次
        $old_item = $this->findUserArticleItem($data['article_id']);
        if(!empty($old_item)){
            $res = [
                'status' => true,
                'msg' => '您已成功申报该项目',
                'data' => ['id' => $old_item['id']],
            ];
            return $res;
        }

        $validate = new Validate;
        // 默认验证场景名
        if(!$validate->check($data)){
            $res['msg'] = $validate->getError();
            return $res;
        }

        if(isset($data['id']) && $data['id'] > 0){
            $item = $this->where('id', $data['id'])->find();
        }else{
            $item = [];
        }
        if(empty($item)){
            $is_update = false;
            $msg = '提交项目申报成功';
        }else{
            $is_update = true;
            $msg = '更新项目申报成功';
            $data['id'] = $item['id'];
        }
        $this->data($data)->isUpdate($is_update)->allowField(true)->save();

        $res = [
            'status' => true,
            'msg' => $msg,
            'data' => ['id' => $this->id],
        ];
        return $res;
    }


    /**
     * 删除记录
     * @Author   zhanghong(Laifuzi)
     * @DateTime 2018-06-12
     * @param    [type]             $id [description]
     * @return   [type]                 [description]
     */
    public function deleteItem($id)
    {
        $res = [
            'status' => false,
            'msg' => '删除失败',
            'data' => ['id' => $id],
        ];
        return $res;
    }

    /**
     * 转化查询条件
     * @Author   zhanghong(Laifuzi)
     * @DateTime 2018-06-07
     * @param    array              $param [description]
     * @return   array                     [description]
     */
    private function parseSearchParam($param)
    {
        $map = [];
        foreach ($param as $key => $value) {
            if(!is_array($value)){
                $value = trim($value);
            }
            switch ($key) {
            case 'id':
            case 'user_id':
                $map[] = [$key, '=', intval($value)];
                break;
            case 'except_id':
                $map[] = ['id', '<>', intval($value)];
                break;
            case "egt_time":
                $val = strtotime($value);
                if($val>=946656000){
                    $map[] = ['create_time', '>=', $val];
                }
                break;
            case "elt_time":
                $val = strtotime($value.' 23:59:59');
                if($val>=946656000){
                    $map[] = ['create_time', '<=', $val];
                }
                break;
            case "keyword":
                if(empty($value)){
                    continue;
                }else{
                    $keyword = "%{$value}%";
                }
                $map[] = ["title|user_name|mobile|college_name", "like", $keyword];
                break;
            }
        }
        return $map;
    }

    /**
     * 搜索排序方式
     * @Author   zhanghong(Laifuzi)
     * @DateTime 2018-06-07
     * @param    string             $param 排序方式
     * @return   string                    [description]
     */
    protected function queryOrderStr($order_type = '')
    {
        switch ($order_type) {
            default:
                $str = 'id DESC';
                break;
        }
        return $str;
    }

    /**
     * 导出字段列表
     * @Author   zhanghong(Laifuzi)
     * @DateTime 2018-06-21
     * @return   [type]             [description]
     */
    private function exportHeaders(){
        return [
            ['name' => 'id', 'title' => 'ID', 'type' => 'string', 'default' => ''],
            ['name' => 'user_login_name', 'title' => '注册用户登录名', 'type' => 'string', 'default' => ''],
            ['name' => 'user_mobile', 'title' => '注册用户手机', 'type' => 'string', 'default' => ''],
            ['name' => 'article_title', 'title' => '申报项目', 'type' => 'string', 'default' => ''],
            ['name' => 'title', 'title' => '论文名称', 'type' => 'string', 'default' => ''],
            ['name' => 'user_name', 'title' => '姓名', 'type' => 'string', 'default' => ''],
            ['name' => 'gender', 'title' => '性别', 'type' => 'string', 'default' => ''],
            ['name' => 'birthday', 'title' => '出生年月', 'type' => 'date', 'default' => ''],
            ['name' => 'id_num', 'title' => '身份证号', 'type' => 'string', 'default' => ''],
            ['name' => 'education', 'title' => '最高学历', 'type' => 'string', 'default' => ''],
            ['name' => 'pro_title', 'title' => '职称', 'type' => 'string', 'default' => ''],
            ['name' => 'email', 'title' => '邮箱', 'type' => 'string', 'default' => ''],
            ['name' => 'mobile', 'title' => '手机号', 'type' => 'string', 'default' => ''],
            ['name' => 'college_name', 'title' => '学校名称', 'type' => 'string', 'default' => ''],
            ['name' => 'college_type', 'title' => '学校类型', 'type' => 'string', 'default' => ''],
            ['name' => 'college_no', 'title' => '机构标识码', 'type' => 'string', 'default' => ''],
            ['name' => 'college_depart', 'title' => '二级院校', 'type' => 'string', 'default' => ''],
            ['name' => 'create_time', 'title' => '提交时间', 'type' => 'date', 'default' => ''],
        ];
    }
}
